/**
 * Created by DELL on 2017/6/15.
 */

import React  from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    PixelRatio,
    TouchableHighlight,
    TouchableOpacity,
    ListView,
    RefreshControl,
    ActivityIndicator

} from 'react-native';

import BaseComponent, {base, AppIndictor} from '../../base/Base' ;
let {
    N028_ORDERS$_GET_ORDERS,// 订单列表
    N029_ORDERS$_CANCEL_ORDERS,// 取消 订单
} = base.requests;


let {
    USER_INFO,
    KEY_PHONE,
} = base.fields;
let pageSize = '4';
let loadFlag = "first"; // first ,refresh ,loadmore

let isFirstTime = false;


export default class OrderListPage extends BaseComponent {
    static navigationOptions = {}

    constructor(props) {
        super(props);
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        var dsChild = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});


        this.state = {

            cellphone: '',
            showIndictor: false,// 加载 提示框


            pageIndex: 1,

            dataSource: ds,
            dataSourceChild: dsChild,
            data: [],

            datas: ds.cloneWithRows([]),


            headLoading: false,//下拉刷新
            isShowBottomRefresh: false,// 底部加载


        }


        //本地获取 电话
        base.Store.get(KEY_PHONE)
            .then(phone => {
                this.setState({cellphone: phone})
            });

    }

    //首次 加载
    componentWillMount() {
        loadFlag = "first";
        this.setState({showIndictor: true});
        this._getOrderList();

    }

    componentDidMount() {


    }

    //联网获取 列表数据
    _getOrderList() {

        var pageIndex = this.state.pageIndex;
        var cellphone = this.state.cellphone;

        let params = {};
        params.cellphone = cellphone;
        params.pageIndex = pageIndex;
        params.pageSize = pageSize;


        base.network.getUipData(N028_ORDERS$_GET_ORDERS, params,
            (successData) => {

                //console.log(JSON.stringify(successData));
                console.log(successData.length);
                if (successData.length > 0) {

                    if (loadFlag === 'loadmore') {
                        // 如果是 加载更多，获取到了 数据 ，追加数据
                        base.toastShort("loadmore");
                        let dataNew = (this.state.data ).concat(successData);
                        this.setState({
                            // isShowBottomRefresh: false,
                            showIndictor: false,
                            data: dataNew,
                            datas: this.state.dataSource.cloneWithRows(dataNew),
                        });


                    } else if (loadFlag === 'refresh') {
                        base.toastShort("refresh");
                        //  刷新， 直接 赋值
                        this.setState({
                            headLoading: false,
                            // showIndictor: false,
                            data: successData,
                            datas: this.state.dataSource.cloneWithRows(successData),
                        });
                    } else { // 第一次

                        base.toastShort("first");
                        this.setState({
                            showIndictor: false,
                            data: successData,
                            datas: this.state.dataSource.cloneWithRows(successData),
                        });
                    }


                } else {

                    // 考虑 加载更多 获取不到数据的情况
                    // 索引 恢复 原来的有数据情况下的最大值
                    if (loadFlag === 'loadmore') {
                        this.setState({
                            showIndictor: false,
                            pageIndex: this.state.pageIndex - 1,
                        })
                    }


                }


            },
            (error) => {
                if ((loadFlag === 'first') || (loadFlag === 'loadmore')) {
                    this.setState({showIndictor: false});
                    base.toastShort('获取失败：' + error);
                }


            });


    }

    //选中了某一项
    orderSelected(itemData) {

        this.props.navigation.navigate("OrderDetailPage", {orderId: itemData.orderId})
    }

    //刷新操作
    reloadData() {
        base.toastShort("开始 刷新");
        loadFlag = "refresh";
        this.setState({
            headLoading: true,
            //showIndictor: true,
            pageIndex: 1,
        });
        this._getOrderList();

    }

    //加载更多
    loadMoreData() {

        // 刷新会执行 加载更多方法 ，在此做下判断,无效
        // if(this.state.headLoading){
        //     return
        // }

        base.toastShort("开始 加载更多");
        loadFlag = 'loadmore';

        if (this.isFirstTime) {
            if (!this.state.showIndictor) {
                this.isFirstTime = false;
            }
            //this.isFirstTime = false;
            return;
        }

        this.isFirstTime = true;
        this.setState({
            //isShowBottomRefresh: true,
            showIndictor: true,
            pageIndex: this.state.pageIndex + 1,
        });

        this._getOrderList();


    }

//     refreshControl={
// <RefreshControl
// refreshing={this.state.headLoading}
// tintColor='#ff0000'
// title='Loading'
// colors={['#ff0000', '#00ff00', '#0000ff']}
// progressBackgroundColor='#ffff00'
// onRefresh={this.reloadData.bind(this)}
//
// />}


    quxiao(order) {
        base.toastShort("取消");
    }

    pay(order) {
        base.toastShort("支付");
    }

    _setList() {
        let data = this.state.data;
        let datas = this.state.datas;

        if (data && data.length > 0) {
            return (

                <ListView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.headLoading}
                            onRefresh={this.reloadData.bind(this)}

                        />}
                    style={{marginTop: 20}}
                    contentContainerStyle={{}}
                    dataSource={datas}
                    renderRow={(rowData) => {
                        return <HomeHotShoppingItem
                            dataSource={rowData}
                            dataSourceChild={this.state.dataSourceChild}
                            onPress={(itemData) => {
                                this.orderSelected(itemData);
                            }}
                            quxiao={(itemData) => {
                                this.quxiao(itemData);
                            }}
                            pay={(itemData) => {
                                this.pay(itemData);
                            }}
                        />
                    }}

                    onEndReached={() => this.loadMoreData()}
                    renderSeparator={() => this.rendSeparator()}
                    stickySectionHeadersEnabled={true}
                    showsVertivalScrollIndicator={false}
                />

            );
        }


    }

    //分割view
    rendSeparator() {
        return <View style={base.styles.line}/>

    }

    // 加载更多后会一直存在
    renderFooter() {
        //return <ActivityIndicator />;

        // if (this.state.isShowBottomRefresh) {
        //     return (<View style={{marginVertical: 10}}>
        //         <ActivityIndicator />
        //     </View>);
        // }
        return <View style={{marginVertical: 10}}/>;

    }

    render() {


        return (

            <View style={[base.styles.container]}>

                {/*加载框*/}
                <AppIndictor
                    modalVisible={this.state.showIndictor}
                    size={'large'}
                    color={'#ff6138'}/>


                {this._setList()}


            </View>
        );


    };
}


class HomeHotShoppingItem extends BaseComponent {

    render() {
        let data = this.props.dataSource;
        //let dsource1 =   this.state.dataSource1;// not
        let dsourceChild = this.props.dataSourceChild;

        let status_text = '';
        let style_text = styles.color_quxiao;
        // //  订单状态： 0 创建待支付 1 已支付，进行中 2 申请退款，20 同意退款，
        // // 21 退款驳回 ，已退款27 退款成功 28 退款失败 3 支付失败 7已完成 8已取消
        if (data.status === ("0")) {

            status_text = "待支付";
            //viewHolder.order_status.setTextColor(0xffFF7B00);
            style_text = styles.color_FF7B00;

            // viewHolder.order_2button.setVisibility(View.VISIBLE);
            // viewHolder.order_totalamount.setText(data.totalAmount);
            // viewHolder.item_ll_order_complete.setVisibility(View.GONE);
        }

        else if (data.status === ("1") || data.status === ("10")) {

            status_text = "待服务中";
            //viewHolder.order_status.setTextColor(0xff2FC1FF);
            style_text = styles.color_server;

            // viewHolder.order_2button.setVisibility(View.GONE);
            // String totalAmount = data.totalAmount;
            // viewHolder.order_totalamount.setText(totalAmount);
            // viewHolder.item_ll_order_complete.setVisibility(View.VISIBLE);
        }
        else if (data.status === ("8") || data.status === ("27")
            || data.status === ("3")) {
            if (data.status === ("8")) {// 已取消
                status_text = "已取消";
                // viewHolder.order_status.setTextColor(0xff808080);
                style_text = styles.color_quxiao;
            } else if (data.status === ("27")) {//退款成功
                status_text = "退款成功";//已退款
                // viewHolder.order_status.setTextColor(0xffAB8770);
                style_text = styles.color_AB8770;
            } else if (data.status === ("3")) {// 支付失败
                status_text = "支付失败";
                // viewHolder.order_status.setTextColor(0xffDA4848);
                style_text = styles.color_AB8770;
            }
            // viewHolder.order_2button.setVisibility(View.GONE);
            // viewHolder.order_totalamount.setText(data.totalAmount);
            // viewHolder.item_ll_order_complete.setVisibility(View.GONE);
        } else if (data.status === ("7") || data.status === ("2") || data.status === ("20")
            || data.status === ("21") || data.status === ("28")) {
            if (data.status === ("7")) {
                status_text = "已完成";
                //viewHolder.order_status.setTextColor(0xff404040);
                style_text = styles.color_com;
            } else if (data.status === ("2")) {
                status_text = "申请退款";
                // viewHolder.order_status.setTextColor(0xffAB8770);
                style_text = styles.color_AB8770;
            } else if (data.status === ("20")) {
                status_text = "同意退款";
                // viewHolder.order_status.setTextColor(0xffAB8770);
                style_text = styles.color_AB8770;
            } else if (data.status === ("21")) {
                status_text = "退款驳回";
                // viewHolder.order_status.setTextColor(0xffAB8770);
                style_text = styles.color_AB8770;
            } else if (data.status === ("28")) {
                status_text = "退款失败";
                //viewHolder.order_status.setTextColor(0xffAB8770);
                style_text = styles.color_AB8770;
            } else {
                Log.e("tag", "getView: OrderAllAdapter 订单的其他状态");
            }

            // viewHolder.order_2button.setVisibility(View.GONE);
            // String totalAmount = data.totalAmount;
            //
            // viewHolder.order_totalamount.setText(totalAmount);
            // viewHolder.item_ll_order_complete.setVisibility(View.GONE);

        }


        return (
        <View>
            <TouchableHighlight
                onPress={this.props.onPress.bind(this, data)}
                underlayColor='#00000000'
            >
                <View
                    style={[base.styles.container, {
                        justifyContent: 'space-around',
                        alignItems: 'flex-start',
                        paddingBottom: 10,
                        paddingTop: 10,
                        backgroundColor: 'white'
                    }]}
                >

                    {/* 鲜花部分*/}
                    <View style={[styles.container_row, {marginLeft: 15, marginRight: 15}]}>
                        <View style={ base.styles.container_row}>
                            <Image style={styles.image} source={{uri: data.serviceCategory.iconUrl}}/>
                            <Text
                                style={[base.styles.home_text_16_212121, {marginLeft: 10}]}>
                                {data.serviceCategory.name}
                            </Text>

                        </View>


                        <View style={{marginLeft: 40}}>
                            <Text style={ style_text }>{status_text}</Text>
                        </View>

                    </View>


                    {/* 商品列表部分 */}
                    <ListView
                        style={{width: base.StyleConfig.screen_width}}
                        contentContainerStyle={{backgroundColor: '#f5f5f5'}}
                        dataSource={dsourceChild.cloneWithRows(data.goods)}
                        renderRow={(rowData) => {
                            return <HotShoppingItem
                                dataSource={rowData}


                            />
                        }}

                        stickySectionHeadersEnabled={true}
                        showsVertivalScrollIndicator={false}
                    />


                    {/* 共计 部分*/}

                    <View style={[styles.container_row1, {width: base.StyleConfig.screen_width, marginLeft: 15}]}>
                        <Text style={base.styles.home_text_16_212121}>
                            共计 {data.goodsCount } 件商品 实付总价
                        </Text>

                        <Image style={base.styles.home_renmingbi1_image}
                               source={ require('../../imgs/goods/renmingbi1.png')}/>
                        <Text
                            style={base.styles.order_text_16_FF6138}>
                            {data.totalAmount}
                        </Text>


                    </View>



                </View>
            </TouchableHighlight>

            {/*  底部的 确认 取消*/}
            { this.setOrderBottom(data)}

        </View>


        )
    }

    setOrderBottom(data) {

       // if (data.status === ("0")) {

            return ( <View style={[styles.container_row1_end, {width: base.StyleConfig.screen_width, marginRight: 15,backgroundColor:"white"}]}>
                    <TouchableOpacity onPress={this.props.quxiao.bind(this, data)}>
                        <Text


                            style={base.styles.order_text_16_808080_border}>
                            取消订单
                        </Text>
                    </TouchableOpacity>


                    <TouchableOpacity  onPress={this.props.pay.bind(this, data)}
                    >
                        <Text

                            style={[base.styles.order_text_16_FF6138_border,{marginLeft:15}]}>
                            立即支付
                        </Text>
                    </TouchableOpacity>

                </View>
            );
        // }else if(data.status === ("21")){
        //
        //     return ( <View style={[styles.container_row1_end, {width: base.StyleConfig.screen_width, marginRight: 15}]}>
        //             <Text
        //                 onPress={this.quxiao.bind(this, data.orderid)}
        //                 style={base.styles.order_text_16_808080_border}>
        //                 取消订单
        //             </Text>
        //
        //         </View>
        //     );
        // }else {
        //     return (<View></View>);
        // }


    }



}

//第二层listview 的item
class HotShoppingItem extends BaseComponent {

    render() {
        //获取传递的数据
        let good = this.props.dataSource;
        return (

            <View
                style={[styles.container_row, {justifyContent: "space-between",}]}>
                <View style={{flexDirection: 'row', marginLeft: 15}}>
                    <Image style={styles.recommend_image} source={{uri: good.iconUrl}}/>
                    <Text
                        style={base.styles.home_text_16_212121}>
                        {good.name}
                    </Text>

                </View>


                {/*      价格*/}

                <View style={{alignItems: 'center', marginRight: 15}}>
                    <Text
                        style={base.styles.home_text_16_212121}> ¥ :{good.price}

                    </Text>
                    {/*数量 :*/}
                    <Text
                        style={base.styles.home_text_16_212121}> *{good.amount}

                    </Text>
                </View>


            </View>

        )
    }

}


const styles = StyleSheet.create({
    color_quxiao: {

        color: '#808080',
    },
    color_server: {
        color: '#2FC1FF',
    },
    color_com: {
        color: '#FF6138',
    },
    color_AB8770: {
        color: '#AB8770',
    },
    color_FF7B00: {
        color: '#FF7B00',
    },

    image: {
        width: 15,
        height: 15,

    },
    list: {
        marginTop: 5,
        justifyContent: 'space-around',
        flexDirection: 'row',
        flexWrap: 'wrap'
    },

    container_row: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "space-around",
        alignItems: "center",


    },


    container_row1: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "flex-start",
        alignItems: "center",


    },
    container_row1_end: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "flex-end",
        alignItems: "center",


    },
    recommend_image: {
        width: 40,
        height: 40,
    }


});
